import {NetSetting} from "@/setting";

/**
 * Jwt操作工具库，提供了一系列方便函数
 */

// 创建Authorization头部
function createAuthorizationHeader(...args: string[]): string {
    return args.join(" ");
}

function getAccessToken(): string | null {
    return localStorage.getItem(NetSetting.accessKey);
}

function getRefreshToken(): string | null {
    return localStorage.getItem(NetSetting.refreshKey);
}

function setAccessToken(token: string) {
    localStorage.setItem(NetSetting.accessKey, token);
}

function setRefreshToken(token: string) {
    localStorage.setItem(NetSetting.refreshKey, token);
}

function clearAuth() {
    localStorage.removeItem(NetSetting.accessKey);
    localStorage.removeItem(NetSetting.refreshKey);
    localStorage.removeItem(NetSetting.userKey);
    localStorage.removeItem(NetSetting.useruuid);
}

// 解析token中的用户信息
function parseTokenInfo() {
    const token = getAccessToken();
    if (token === null) return;
    // 解码jwt中的payload部分
    const payload = token.split(".")[1];
    // Base64解码
    const originalPayload = decodeURIComponent(window.atob(payload));
    // json反序列化
    const data: JwtPayload = JSON.parse(originalPayload);
    // 解析出jwt payload部分的数据
    if (data.userId != null) {
        localStorage.setItem(NetSetting.userKey, data.userId);
    }
    if (data.userUUID != null) {
        localStorage.setItem(NetSetting.useruuid, data.userUUID);
    }
}

// 获取用户基本信息
function takeUserInfoLocal(): JwtPayload {
    return new JwtPayload(localStorage.getItem(NetSetting.userKey), localStorage.getItem(NetSetting.useruuid));
}

export const JwtUtils = {
    createAuthorizationHeader,
    getAccessToken,
    getRefreshToken,
    setRefreshToken,
    setAccessToken,
    parseTokenInfo,
    takeUserInfoLocal,
    clearAuth
};